package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 聊天室的客户端
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("正在连接服务器...");
            socket = new Socket("localhost",8088);//localhost表示本机IP
            System.out.println("与服务器建立连接成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void start(){
        try {
            OutputStream os  = socket.getOutputStream();//低级流,作用:将写出的字节发送给建立连接的远程计算机(说白了就是服务器)
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);//自动行刷新

            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {//关闭socket即可,相当于关闭手机
                socket.close();//与服务器断开连接
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }
}
